package weibo.acitivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.ImageLoader;


import java.util.ArrayList;
import java.util.List;

import inter.Delegate;
import inter.ResponseStatus;
import managers.UIHandler;
import model.Blog;
import model.OwnUser;
import utils.TimeUtil;
import weibo.adapter.CommitAdapter;
import weibo.network.GetCommit;
import weibo.network.SendCommit;

/**
 * 评论区
 * Created by Administrator on 2016/4/15.
 */
public class CommitActivity extends UIHandler.BaseActivity {

    PullToRefreshScrollView pullToRefreshScrollView;

    ListView lv_commit;
    TextView tv_name;
    TextView tv_text;
    TextView tv_time;

    Button btn_send;
    EditText et_content;
    //    long blog_ID;
    OwnUser ownUser = MyApplication.getOwnUser();
    Blog blog;
    CommitAdapter commitAdapter = new CommitAdapter();

    // 获取之前评论
    Delegate commitList = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (pullToRefreshScrollView.isRefreshing())
                pullToRefreshScrollView.onRefreshComplete();
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            GetCommit.ResponseGetComment responseGetComment = gson.fromJson(response, GetCommit.ResponseGetComment.class);
            if (responseGetComment.getStatus().equals(ResponseStatus.SUCCESS)) {
                commitAdapter.setResponseGetComment(responseGetComment);
                commitAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MyApplication.share(), "网络异常", Toast.LENGTH_SHORT).show();
            if (pullToRefreshScrollView.isRefreshing())
                pullToRefreshScrollView.onRefreshComplete();
        }
    };

    GetCommit getCommit = new GetCommit();
    private List<ImageView> imageViews = new ArrayList<ImageView>();

    {
        getCommit.setDelegate(commitList);
    }


    // 发送评论
    Delegate commitResult = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("{")) return;
            Gson gson = new Gson();
            SendCommit.ResponseBlogComment responseBlogComment = gson.fromJson(response, SendCommit.ResponseBlogComment.class);
            if (responseBlogComment.getStatus().equals(ResponseStatus.SUCCESS)) {
                Toast.makeText(MyApplication.share(),"发送成功",Toast.LENGTH_SHORT).show();
                getCommit.get();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MyApplication.share(),"发送失败",Toast.LENGTH_SHORT).show();
        }
    };


    SendCommit sendCommit = new SendCommit();

    {
        sendCommit.setDelegate(commitResult);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commit_boke);
        initview();
        initdata();

    }

    private void initdata() {
        blog = (Blog) getIntent().getSerializableExtra("blog");
        getCommit.setBlog_ID(blog.getBlog_ID() + "");
        getCommit.get();

        tv_name.setText(blog.getUser_Name() + "");
        tv_time.setText(blog.getBlog_Time());
        tv_text.setText(blog.getBlog_Text());

        if (blog.getBlog_Text() == null || blog.getBlog_Text().isEmpty()) {
            tv_text.setVisibility(View.GONE);
        } else {
            tv_text.setVisibility(View.VISIBLE);
        }

        hideAllImgs();
        if (blog.getImage_Num() != 0) {
            String[] filenames = blog.getImage_Set().split(";");
            int j = 0;
            for (int i = 0; i < filenames.length; i++) {
                if (filenames[i].isEmpty()) continue;
                String ip = MyApplication.share().getString(R.string.IP);
                final int mJ = j;
                imageViews.get(j).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(UIHandler.uiHandler.getActivityByName(CommitActivity.class.getSimpleName()), MyPhotoActivity.class);
                        intent.putExtra("blog", blog);
                        intent.putExtra("position", mJ);
                        UIHandler.uiHandler.getActivityByName(CommitActivity.class.getSimpleName()).startActivity(intent);

                    }
                });
                ImageLoader.getInstance().displayImage("http://" + ip + "/Blog/DownloadFile?name=" + filenames[i] + "_sm", imageViews.get(j++), MyApplication.options);

            }
            showImgs(blog.getImage_Num());
        }
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_send) {
                commit();
            }
        }
    };

    private void commit() {
        if (et_content.getText().toString().isEmpty())
        {
            Toast.makeText(MyApplication.share(),"评论不能为空",Toast.LENGTH_SHORT).show();
        }


        SendCommit.CommentBlog commentBlog = new SendCommit.CommentBlog();
        commentBlog.setComment_Time(TimeUtil.currentTime());
        commentBlog.setComment_Content(et_content.getText().toString());
        commentBlog.setBlog_ID(blog.getBlog_ID() + "");
        commentBlog.setUser_ID(ownUser.getUser_ID());
        sendCommit.setCommentBlog(commentBlog);
        sendCommit.send();
        et_content.setText("");
    }

    private void initview() {
        lv_commit = (ListView) findViewById(R.id.id_lv_commit);
        lv_commit.setAdapter(commitAdapter);
        lv_commit.setDividerHeight((int) getResources().getDimension(R.dimen.y4));

        addAllImgs(imageViews, R.id.id_img0, R.id.id_img1, R.id.id_img2, R.id.id_img3, R.id.id_img4, R.id.id_img5);

        tv_name = (TextView) findViewById(R.id.id_tv_name);
        tv_text = (TextView) findViewById(R.id.id_tv_text);
        tv_time = (TextView) findViewById(R.id.id_tv_time);

        btn_send = (Button) findViewById(R.id.id_btn_send);
        btn_send.setOnClickListener(onClickListener);
        et_content = (EditText) findViewById(R.id.id_et_message);

        pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.id_scrollview);
        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getCommit.get();
            }
        });
    }

    public void addAllImgs(List<ImageView> imageViews, int... ids) {
        for (int id : ids) {
            imageViews.add((ImageView) findViewById(id));
        }
    }

    // 显示图片
    private void showImgs(int image_num) {
        for (int i = 0; i < image_num; i++) {
            imageViews.get(i).setVisibility(View.VISIBLE);
        }
    }

    public void hideAllImgs() {
        for (ImageView imageView : imageViews) {
            imageView.setVisibility(View.GONE);
        }
    }

}
